<template>
  <view class="order-manage">
    <view class="search-bar">
      <input 
        type="text" 
        v-model="searchKeyword" 
        placeholder="搜索订单号/用户名" 
        @input="handleSearch"
      />
      <view class="filter-group">
        <picker 
          mode="selector" 
          :range="orderStatusOptions" 
          range-key="label"
          @change="handleStatusFilter"
        >
          <view class="picker">
            状态：{{ currentStatus ? currentStatus.label : '全部' }}
          </view>
        </picker>
        <picker 
          mode="date" 
          :value="dateFilter" 
          @change="handleDateFilter"
        >
          <view class="picker">
            日期：{{ dateFilter || '全部' }}
          </view>
        </picker>
        <button class="refresh-btn" @click="fetchOrderList">刷新</button>
      </view>
    </view>
    
    <view class="data-stats">
      <text class="stats-text">显示 {{ orderList.length }} 条订单{{ totalOrders > orderList.length ? `（共 ${totalOrders} 条）` : '' }}</text>
    </view>
    
    <view class="order-table">
      <view class="table-header">
        <view class="th">订单号</view>
        <view class="th">用户账号</view>
        <view class="th">商品信息</view>
        <view class="th">订单金额</view>
        <view class="th">订单状态</view>
        <view class="th">下单时间</view>
        <view class="th">操作</view>
      </view>
      <view class="table-body">
        <view v-if="orderList.length === 0" class="empty-data">
          <text class="empty-text">暂无订单数据</text>
        </view>
        <view v-else v-for="order in orderList" :key="order._id" class="table-row">
          <view class="td">{{ order.order_no || order.orderNo }}</view>
          <view class="td user-info">
            <text>{{ order.account || order.customer }}</text>
          </view>
          <view class="td product-info">
            <view v-for="(item, index) in order.products" :key="index" class="product-item">
              <image :src=" url('sp', item.product.id-1, 'png')" mode="aspectFill" />
              <view class="product-detail">
                <text class="name">{{ item.name }}</text>
                <text class="spec">数量: {{ item.quantity }}</text>
              </view>
            </view>
          </view>
          <view class="td">¥{{ order.total_amount || order.total_price }}</view>
          <view class="td">
            <text :class="['status-tag', order.status]">{{ getStatusText(order.status) }}</text>
          </view>
          <view class="td">{{ formatDate(order.create_time || order.createTime) }}</view>
          <view class="td">
            <text class="action-btn" @click="handleViewDetail(order)">查看</text>
            <text v-if="order.status === 'pending'" class="action-btn" @click="handleUpdateStatus(order, 'shipping')">发货</text>
            <text v-if="order.status === 'shipping' || order.status === 'processing'" class="action-btn" @click="handleUpdateStatus(order, 'review')">确认收货</text>
            <text v-if="order.status === 'review'" class="action-btn" @click="handleUpdateStatus(order, 'completed')">完成</text>
            <text class="action-btn delete" @click="handleDelete(order)">删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 订单详情弹窗 -->
    <uni-popup ref="detailPopup" type="center">
      <view class="popup-content">
        <view class="popup-title">订单详情</view>
        <view class="detail-content" v-if="currentOrder">
          <view class="detail-item">
            <text class="label">订单号：</text>
            <text class="value">{{ currentOrder.order_no || currentOrder.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="label">下单时间：</text>
            <text class="value">{{ formatDate(currentOrder.create_time || currentOrder.createTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">订单状态：</text>
            <text class="value">{{ getStatusText(currentOrder.status) }}</text>
          </view>
          <view v-if="currentOrder.trackingNumber" class="detail-item">
            <text class="label">快递单号：</text>
            <text class="value">{{ currentOrder.trackingNumber }}</text>
          </view>
          <view v-if="currentOrder.shippingTime" class="detail-item">
            <text class="label">发货时间：</text>
            <text class="value">{{ formatDate(currentOrder.shippingTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">用户账号：</text>
            <text class="value">{{ currentOrder.account || currentOrder.customer }}</text>
          </view>
          <view class="detail-item">
            <text class="label">收货信息：</text>
            <view class="value">
              <text>{{ (currentOrder.address && currentOrder.address.name) || (currentOrder.shippingInfo && currentOrder.shippingInfo.name) || '未提供' }}</text>
              <text>{{ (currentOrder.address && currentOrder.address.phone) || (currentOrder.shippingInfo && currentOrder.shippingInfo.phone) || '未提供' }}</text>
              <text>{{ formatAddress(currentOrder.address || currentOrder.shippingInfo) }}</text>
            </view>
          </view>
          <view class="detail-item">
            <text class="label">商品信息：</text>
            <view class="value product-list">
              <view v-for="(item, index) in currentOrder.products" :key="index" class="product-item">
                <image :src="url('sp', item.id-1, 'png')" mode="aspectFill" />
                <view class="product-detail">
                  <text class="name">{{ item.name }}</text>
                  <text class="price">¥{{ item.price }} x {{ item.quantity }}</text>
                </view>
              </view>
            </view>
          </view>
          <view class="detail-item">
            <text class="label">订单金额：</text>
            <text class="value price">¥ {{ currentOrder.total_amount || currentOrder.total_price }}</text>
          </view>
          <view class="detail-item">
            <text class="label">备注：</text>
            <text class="value">{{ currentOrder.remark || currentOrder.note || '无' }}</text>
          </view>
        </view>
        <view class="btn-group">
          <button @click="closeDetail">关闭</button>
          <button v-if="currentOrder && currentOrder.status === 'pending'" @click="handleUpdateFromDetail('shipping')">发货</button>
          <button v-if="currentOrder && currentOrder.status === 'shipping'" @click="handleUpdateFromDetail('review')">确认收货</button>
          <button v-if="currentOrder && currentOrder.status === 'review'" @click="handleUpdateFromDetail('completed')">完成</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const url = $url
const searchKeyword = ref('')
const orderList = ref([])
const currentOrder = ref(null)
const dateFilter = ref('')
const currentStatus = ref(null)
const detailPopup = ref(null)
const totalOrders = ref(0) // 总订单数量

const orderStatusOptions = [
  { value: '', label: '全部' },
  { value: 'pending', label: '待发货' },
  { value: 'shipping', label: '已发货' },
  { value: 'review', label: '已收货' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
]

const fetchOrderList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    // 构建请求参数
    const params = {
      keyword: searchKeyword.value,
      status: currentStatus.value?.value || '',
      page: 1,
      pageSize: 100  // 增大分页大小，确保获取全部数据
    }
    
    // 执行请求
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getOrderList',
          ...params
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      console.log('订单数据总数:', res.result.data?.length || 0)
      
      // 保存总订单数量
      totalOrders.value = res.result.total || res.result.data?.length || 0
      
      // 确保将数据存入orderList
      orderList.value = res.result.data || []
      
      // 如果有日期过滤，进行前端过滤
      if (dateFilter.value) {
        const filterDate = new Date(dateFilter.value).setHours(0, 0, 0, 0)
        orderList.value = orderList.value.filter(order => {
          const dateField = order.create_time || order.createTime
          if (!dateField) return false
          const orderDate = new Date(dateField).setHours(0, 0, 0, 0)
          return orderDate === filterDate
        })
      }
      
      console.log('过滤后的订单数据:', orderList.value.length)
    } else {
      console.error('获取订单列表失败:', res.result)
      uni.showToast({
        title: res.result?.message || '获取订单列表失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取订单列表失败:', error)
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    })
  }
}

const handleSearch = () => {
  fetchOrderList()
}

const handleStatusFilter = (e) => {
  currentStatus.value = orderStatusOptions[e.detail.value]
  fetchOrderList()
}

const handleDateFilter = (e) => {
  dateFilter.value = e.detail.value
  fetchOrderList()
}

const handleViewDetail = async (order) => {
  try {
    uni.showLoading({ title: '加载中...' })
    
    // 先获取最新的订单详情
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getOrderById',
          orderId: order._id
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      currentOrder.value = res.result.data
      detailPopup.value.open()
    } else {
      uni.showToast({
        title: res.result?.message || '获取订单详情失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取订单详情失败:', error)
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    })
  }
}

const handleUpdateStatus = async (order, newStatus) => {
  try {
    // 如果是发货状态，需要先请求快递单号
    if (newStatus === 'shipping' || newStatus === 'processing') {
      uni.showModal({
        title: '发货',
        content: '请填写快递单号',
        editable: true,
        placeholderText: '请输入快递单号',
        success: async (res) => {
          if (res.confirm) {
            const trackingNumber = res.content || '';
            
            if (!trackingNumber.trim()) {
              uni.showToast({
                title: '快递单号不能为空',
                icon: 'none'
              });
              return;
            }
            
            await updateOrderWithTracking(order, newStatus, trackingNumber);
          }
        }
      });
    } else {
      // 其他状态不需要快递单号
      uni.showModal({
        title: '确认操作',
        content: `确定将订单状态更改为"${getStatusText(newStatus)}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            await updateOrderWithTracking(order, newStatus);
          }
        }
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('更新订单状态失败:', error);
    uni.showToast({
      title: '更新订单状态失败',
      icon: 'none'
    });
  }
};

// 更新订单状态并可选地添加快递单号
const updateOrderWithTracking = async (order, newStatus, trackingNumber = '') => {
  uni.showLoading({ title: '更新中...' });
  
  // 构建更新数据
  const updateData = {
    status: newStatus
  };
  
  // 如果提供了快递单号，添加到更新数据中
  if (trackingNumber) {
    updateData.trackingNumber = trackingNumber;
    updateData.shippingTime = Date.now(); // 添加发货时间
  }
  
  try {
    const result = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'updateOrderStatus',
          orderId: order._id,
          status: newStatus,
          updateData: updateData // 传递完整的更新数据
        })
      }
    });
    
    uni.hideLoading();
    
    if (result.result && result.result.code === 0) {
      uni.showToast({
        title: '状态更新成功',
        icon: 'success'
      });
      fetchOrderList();
    } else {
      uni.showToast({
        title: result.result?.message || '状态更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('更新订单状态失败:', error);
    uni.showToast({
      title: '更新订单状态失败',
      icon: 'none'
    });
  }
};

const handleUpdateFromDetail = (newStatus) => {
  if (!currentOrder.value) return
  
  // 关闭详情弹窗
  closeDetail()
  
  // 执行状态更新，这样会触发handleUpdateStatus中的逻辑
  handleUpdateStatus(currentOrder.value, newStatus)
}

const handleDelete = (order) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除订单"${order.order_no}"吗？此操作不可恢复！`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          
          const result = await uniCloud.callFunction({
            name: 'alldata',
            data: {
              body: JSON.stringify({
                action: 'deleteOrder',
                orderId: order._id
              })
            }
          })
          
          uni.hideLoading()
          
          if (result.result && result.result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            fetchOrderList()
          } else {
            uni.showToast({
              title: result.result?.message || '删除失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.hideLoading()
          console.error('删除订单失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待发货',
    shipping: '已发货',
    review: '已收货',
    completed: '已完成',
    cancelled: '已取消',
    // 兼容旧状态
    processing: '已发货'
  }
  return statusMap[status] || status
}

const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

const formatAddress = (address) => {
  if (!address) return '未提供地址'
  
  let result = []
  
  // 处理第一种格式 (address包含province, city, district, detail)
  if (address.province || address.city || address.district || address.detail) {
    if (address.province) result.push(address.province)
    if (address.city) result.push(address.city)
    if (address.district) result.push(address.district)
    if (address.detail) result.push(address.detail)
  } 
  // 处理第二种格式 (shippingInfo包含addressLine1, city, state, zip)
  else if (address.addressLine1 || address.city || address.state || address.zip) {
    if (address.addressLine1) result.push(address.addressLine1)
    if (address.city) result.push(address.city)
    if (address.state) result.push(address.state)
    if (address.zip) result.push(address.zip)
  }
  // 如果是完整地址字符串
  else if (typeof address === 'string') {
    return address
  }
  
  return result.join(' ') || '未提供详细地址'
}

const closeDetail = () => {
  detailPopup.value.close()
}

onMounted(() => {
  fetchOrderList()
})
</script>

<style lang="scss" scoped>
.order-manage {
  padding: 20rpx;
  
  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    input {
      flex: 1;
      height: 80rpx;
      border: 1px solid #ddd;
      border-radius: 10rpx;
      padding: 0 20rpx;
      margin-right: 20rpx;
    }
    
    .filter-group {
      display: flex;
      align-items: center;
      
      .picker {
        padding: 0 20rpx;
        height: 80rpx;
        line-height: 80rpx;
        border: 1px solid #ddd;
        border-radius: 10rpx;
        margin-right: 20rpx;
        background-color: #fff;
      }
      
      .refresh-btn {
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 30rpx;
        background-color: #1890ff;
        color: #fff;
        border-radius: 10rpx;
      }
    }
  }
  
  .data-stats {
    margin-bottom: 30rpx;
    
    .stats-text {
      color: #999;
      font-size: 28rpx;
    }
  }
  
  .order-table {
    background-color: #fff;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .table-header {
      display: flex;
      background-color: #fafafa;
      border-bottom: 1px solid #f0f0f0;
      
      .th {
        flex: 1;
        padding: 20rpx;
        text-align: center;
        font-weight: bold;
        
        &:first-child {
          flex: 1.5;
        }
        
        &:nth-child(3) {
          flex: 1.5;
        }
      }
    }
    
    .table-body {
      .empty-data {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999;
          font-size: 28rpx;
        }
      }
      
      .table-row {
        display: flex;
        border-bottom: 1px solid #f0f0f0;
        
        &:hover {
          background-color: #f9f9f9;
        }
        
        .td {
          flex: 1;
          padding: 20rpx;
          text-align: center;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          font-size: 28rpx;
          
          &:first-child {
            flex: 1.5;
            word-break: break-all;
          }
          
          &:nth-child(3) {
            flex: 1.5;
          }
          
          .status-tag {
            display: inline-block;
            padding: 6rpx 16rpx;
            border-radius: 30rpx;
            font-size: 24rpx;
            
            &.pending {
              background-color: #e6f7ff;
              color: #1890ff;
            }
            
            &.shipping, &.processing {
              background-color: #f6ffed;
              color: #52c41a;
            }
            
            &.review {
              background-color: #fff7e6;
              color: #fa8c16;
            }
            
            &.completed {
              background-color: #f9f9f9;
              color: #999;
            }
            
            &.cancelled {
              background-color: #fff1f0;
              color: #ff4d4f;
            }
          }
          
          .action-btn {
            color: #1890ff;
            margin: 10rpx;
            cursor: pointer;
            
            &.delete {
              color: #ff4d4f;
            }
          }
          
          .user-info, .product-info {
            text {
              display: block;
              margin-bottom: 10rpx;
            }
          }
          
          .product-item {
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;
            
            image {
              width: 80rpx;
              height: 80rpx;
              border-radius: 10rpx;
              margin-right: 10rpx;
            }
            
            .product-detail {
              text-align: left;
              
              .name {
                display: block;
                font-size: 24rpx;
                width: 120rpx;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              
              .spec, .price {
                display: block;
                font-size: 22rpx;
                color: #999;
              }
            }
          }
        }
      }
    }
  }
  
  .popup-content {
    width: 700rpx;
    max-width: 90vw;
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    max-height: 80vh;
    overflow-y: auto;
    
    .popup-title {
      font-size: 36rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .detail-content {
      .detail-item {
        margin-bottom: 20rpx;
        
        .label {
          font-weight: bold;
          color: #666;
          margin-right: 10rpx;
        }
        
        .value {
          text {
            display: block;
            margin-bottom: 10rpx;
          }
          
          &.price {
            color: #ff4d4f;
            font-weight: bold;
          }
        }
        
        .product-list {
          margin-top: 10rpx;
          
          .product-item {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            
            image {
              width: 100rpx;
              height: 100rpx;
              border-radius: 10rpx;
              margin-right: 20rpx;
            }
            
            .product-detail {
              .name {
                font-size: 28rpx;
                margin-bottom: 10rpx;
              }
              
              .price {
                font-size: 26rpx;
                color: #ff4d4f;
              }
            }
          }
        }
      }
    }
    
    .btn-group {
      display: flex;
      justify-content: center;
      margin-top: 30rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f0f0f0;
      
      button {
        margin: 0 20rpx;
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 40rpx;
        font-size: 28rpx;
        
        &:first-child {
          background-color: #f5f5f5;
          color: #666;
        }
        
        &:not(:first-child) {
          background-color: #1890ff;
          color: #fff;
        }
      }
    }
  }
}
</style> 